package com.leedsoft.news2.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.leedsoft.news2.R;
import com.leedsoft.news2.model.News;


import java.util.List;

public class NewsAdapter extends BaseAdapter {
	private Context context;
	private List<News> news;
	private LayoutInflater inflater;
	private ImageLoader imageLoder;

	public NewsAdapter(Context context, List<News> news, RequestQueue queue){
		this.context = context;
		this.news = news;
		this.inflater = LayoutInflater.from(context);
		this.imageLoder = new ImageLoader(queue, new LruCacheImpl());
	}
	public class LruCacheImpl implements ImageLoader.ImageCache {

		private LruCache<String, Bitmap> mCache;
		public LruCacheImpl(){
			int maxSize = 20*1024*1024;
			mCache = new LruCache<String, Bitmap>(maxSize){
				@Override
				protected int sizeOf(String key, Bitmap bitmap) {
					// TODO Auto-generated method stub
					return bitmap.getRowBytes()*bitmap.getHeight();
				}
			};

		}

		@Override
		public Bitmap getBitmap(String url) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void putBitmap(String url, Bitmap bitmap) {
			// TODO Auto-generated method stub

		}

	}


	@Override
	public int getCount() {
		return news.size();
	}

	@Override
	public News getItem(int position) {
		return news.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if(convertView == null){
			convertView = inflater.inflate(R.layout.list_template, null);
			holder = new ViewHolder();
			holder.ivnews = (ImageView) convertView.findViewById(R.id.title_imageView);
			holder.tvnews = (TextView) convertView.findViewById(R.id.title_textView);
			convertView.setTag(holder);

		}
		holder = (ViewHolder) convertView.getTag();
		//给holder中的控件赋值
		News n =  getItem(position);
		holder.tvnews.setText(n.getTitle());
		//给ivnews设置图片
		//通过网络图片路径 下载图片 然后设置图片

		if (n.getImageurls().size() > 0) {
			String path =n.getImageurls().get(0).getUrl();
			//加载图片
			ImageLoader.ImageListener l = ImageLoader.getImageListener(holder.ivnews, R.mipmap.ic_launcher, R.mipmap.ic_launcher);
			imageLoder.get(path, l);
		}
		return convertView;
	}
	class ViewHolder{
		ImageView ivnews;
		TextView tvnews;
	}

}
